package com.jshan.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import com.jshan.common.annotation.OperationLog;
import com.jshan.base.entity.SysContent;
import com.jshan.enums.FileUploadEnum;
import com.jshan.service.SysContentService;
import com.jshan.utils.ExportDocUtils;
import com.jshan.utils.FileUploadUtils;
import com.jshan.base.vo.Result;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

@Tag(name = "内容管理接口")
@RestController
@RequestMapping("/content")
@RequiredArgsConstructor
public class SysContentController {

    private final SysContentService sysContentService;
    private final ExportDocUtils exportDocUtil;
    private final FileUploadUtils fileUploadUtils;

    @Operation(summary = "获取文章分页内容")
    @GetMapping("/page")
    @SaCheckPermission("content:list")
    public Result findPage(@RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam String title) {
        return sysContentService.findPage(pageNum, pageSize, title);
    }

    @OperationLog("添加或更新文章")
    @PostMapping("/addContent")
    @SaCheckPermission(value = { "content:add", "content:update" }, mode = SaMode.OR)
    public Result addContent(@RequestBody SysContent content) {
        if (sysContentService.saveAndUpdate(content)) {
            return Result.ok(200, "添加内容成功");
        }
        return Result.fail(500, "添加内容失败");
    }

    @GetMapping("/exportWord")
    @SaCheckPermission("content:export:word")
    public void exportWord(@RequestParam Long id, HttpServletResponse response) throws Exception {
        SysContent content = sysContentService.getById(id);
        if (content == null) {
            throw new RuntimeException("文章不存在");
        }
        exportDocUtil.exportWord(content, response);
    }

    @OperationLog("删除文章")
    @SaCheckPermission("content:del")
    @DeleteMapping("/del/{id}")
    public Result delContent(@PathVariable Long id) {
        if (sysContentService.removeById(id)) {
            return Result.ok();
        }
        return Result.fail();
    }

    @SaCheckPermission("content:uploadImg")
    @PostMapping("/uploadImg")
    @OperationLog("文章内容上传图片")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        return fileUploadUtils.upload(file, FileUploadEnum.UPLOAD_CONTENT_IMAGE.getCode());
    }

    @PostMapping("/uploadFile")
    @SaCheckPermission("content:uploadFile")
    @OperationLog("文章内容上传文件")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        return fileUploadUtils.upload(file, FileUploadEnum.UPLOAD_CONTENT_FILE.getCode());
    }
}
